package com.elvis.lifecardemo;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVFriendship;
import com.avos.avoscloud.AVFriendshipQuery;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVStatus;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FollowCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.avos.avoscloud.callback.AVFriendshipCallback;
import com.elvis.lifecardemo.bean.Comments;
import com.elvis.lifecardemo.bean.Like;
import com.elvis.lifecardemo.bean.Post;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created by G on 2018/9/29.
 */

public class LeancloudTest {

    Activity activity;
    public LeancloudTest(Activity activity) {
        this.activity = activity;
    }

    private StringBuilder result = new StringBuilder();

    // 测试 SDK 是否正常工作的代码
    public void leanTest() {
        AVObject testObject = new AVObject("TestObject");
        testObject.put("words","Hello World!");
        testObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if(e == null){
                    Log.d("saved","success!");
                }
            }
        });
    }

    public void register(String username, String password) {
        AVUser user = new AVUser();// 新建 AVUser 对象实例
        user.setUsername(username);// 设置用户名
        user.setPassword(password);// 设置密码
//        user.setEmail("123@test.com");//设置邮箱
        user.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    // 注册成功，把用户对象赋值给当前用户 AVUser.getCurrentUser()
                    result.delete(0, result.length());
                    result.append("注册成功");
                    ((MainActivity)activity).showMsg("register()", result.toString());
                } else {
                    // 失败的原因可能有多种，常见的是用户名已经存在。
                    result.delete(0, result.length());
                    result.append("注册失败\n");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("register()", result.toString());
                }
            }
        });
    }

    public void login(final String username, String password) {
        AVUser.logInInBackground(username, password, new LogInCallback<AVUser>() {
            @Override
            public void done(AVUser avUser, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("登录成功");
                    ((MainActivity)activity).showMsg("login()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("登录失败" + username + "\n");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("login()", result.toString());
                }
            }
        });
    }

    public void post(String content) {
        Post product = new Post();
        product.put("title", "tittle");
        product.put("description", content);
        product.put("owner", AVUser.getCurrentUser());
        try {
            product.put("image", new AVFile("productPic1", getImgBytes("/img02.jpg")));
            product.put("image", new AVFile("productPic2", getImgBytes("/img02.jpg")));
        } catch (IOException e) {
            e.printStackTrace();
            result.delete(0, result.length());
            result.append("发帖失败");
            result.append(e.toString());
            ((MainActivity)activity).showMsg("post()", result.toString());
        }
        product.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("发帖成功");
                    ((MainActivity)activity).showMsg("post()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("发帖失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("post()", result.toString());
                }
            }
        });
    }

    public void comment(String content) {
        Comments product = new Comments();
        product.put("title", "tittle");
        product.put("description", content);
        product.put("owner", AVUser.getCurrentUser());
        product.put("post", AVObject.createWithoutData("Post", "5baf89419f54540070570f49"));
        product.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("评论成功");
                    ((MainActivity)activity).showMsg("comment()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("评论失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("comment()", result.toString());
                }
            }
        });
    }

    public void like() {
        Like product = new Like();
        product.put("owner", AVUser.getCurrentUser());
        product.put("post", AVObject.createWithoutData("Post", "5baf89419f54540070570f49"));
        product.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("点赞成功");
                    ((MainActivity)activity).showMsg("comment()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("点赞失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("comment()", result.toString());
                }
            }
        });
    }

    public void getALLPostList() {
        AVQuery<AVObject> avQuery = new AVQuery<>("Post");
        avQuery.orderByDescending("createdAt");
        avQuery.include("owner");
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append(list.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("获取失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                }
            }
        });
    }

    public void getSingleParamsQuery() {
        AVQuery<AVObject> avQuery = new AVQuery<>("Post");
        avQuery.orderByDescending("createdAt");
        //后面的条件会覆盖前面的条件
//        avQuery.whereEqualTo("owner", AVObject.createWithoutData("_User", "5baf86a2ac502e0063401ba8"));
        avQuery.whereEqualTo("owner", AVObject.createWithoutData("_User", "5baf42fbfb4ffe0069581880"));
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append(list.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("获取失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                }
            }
        });
    }

    public void getMultiParamsQuery() {
        AVQuery<AVObject> avQuery1 = new AVQuery<>("Post");
        avQuery1.whereEqualTo("owner", AVObject.createWithoutData("_User", "5baf86a2ac502e0063401ba8"));
        AVQuery<AVObject> avQuery2 = new AVQuery<>("Post");
        avQuery2.whereEqualTo("owner", AVObject.createWithoutData("_User", "5baf42fbfb4ffe0069581880"));
        AVQuery<AVObject> query = AVQuery.or(Arrays.asList(avQuery1, avQuery2));
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append(list.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("获取失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("getPostList()", result.toString());
                }
            }
        });
    }

    public void follow() {
        //关注user3
        AVUser.getCurrentUser().followInBackground("5baf86a2ac502e0063401ba8", new FollowCallback() {
            @Override
            public void done(AVObject object, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("关注成功");
                    ((MainActivity)activity).showMsg("follow()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("关注失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("follow()", result.toString());
                }
            }
        });
    }

    //获取粉丝列表
    public void getFollowers() {
        AVQuery<AVUser> followerQuery = null;
        try {
            followerQuery = AVUser.getCurrentUser().followerQuery(AVUser.class);
        } catch (AVException e) {
            e.printStackTrace();
            result.delete(0, result.length());
            result.append("followerQuery获取失败");
            result.append(e.toString());
            ((MainActivity)activity).showMsg("getFollowers()", result.toString());
        }
// AVQuery<AVUser> followerQuery = AVUser.followerQuery(userA.getObjectId(),AVUser.class); 也可以使用这个静态方法来获取非登录用户的好友关系
        followerQuery.findInBackground(new FindCallback<AVUser>() {
            @Override
            public void done(List<AVUser> avObjects, AVException e) {
                // avObjects 包含了 userA 的粉丝列表
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("获取粉丝成功\n");
                    result.append(avObjects.toString());
                    ((MainActivity)activity).showMsg("getFollowers()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("获取粉丝失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("getFollowers()", result.toString());
                }
            }
        });
    }

    public void getFolloweeAndFollower() {
        AVFriendshipQuery query = AVUser.friendshipQuery("5baf86a2ac502e0063401ba8", AVUser.class);
        query.include("followee");
        query.include("follower");
        query.getInBackground(new AVFriendshipCallback() {
            @Override
            public void done(AVFriendship friendship, AVException e) {
                AVUser user = friendship.getUser(); //获取用户对象本身
                result.delete(0, result.length());
                result.append("获取粉丝成功\n");
                result.append(user.toString());
                result.append("\n");
                result.append("获取粉丝\n");
                result.append(friendship.getFollowers().toString());
                result.append("\n");
                result.append("获取关注列表\n");
                result.append(friendship.getFollowees().toString());
                ((MainActivity)activity).showMsg("getFollowers()", result.toString());
            }
        });
    }

    public void getUserData() {
        AVQuery<AVUser> userQuery = new AVQuery<>("_User");
        userQuery.whereEqualTo("owner", AVObject.createWithoutData("_User", "5baf86a2ac502e0063401ba8"));
        userQuery.getInBackground("5baf4864ac502e00633b04a0", new GetCallback<AVUser>() {
            @Override
            public void done(AVUser avUser, AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("查询User成功\n");
                    result.append(avUser.toString());
                    ((MainActivity)activity).showMsg("getUserData()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("查询User失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("getUserData()", result.toString());
                }
            }
        });
    }

    public void sendMsg1(String string) {
        AVStatus status = AVStatus.createStatus("test image", "test message");
        AVStatus.sendPrivateStatusInBackgroud(status, "5baf42fbfb4ffe0069581880", new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    result.delete(0, result.length());
                    result.append("发送成功");
                    ((MainActivity)activity).showMsg("follow()", result.toString());
                } else {
                    result.delete(0, result.length());
                    result.append("发送失败");
                    result.append(e.toString());
                    ((MainActivity)activity).showMsg("follow()", result.toString());
                }
            }
        });
    }

    private byte[] getImgBytes(String name) throws IOException {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + name;
        InputStream inputStream = new FileInputStream(path);
        byte[] b = new byte[10240];
        inputStream.read(b);
        //        inputStream.close();
        return b;
    }
}
